package com.itcast.activiti.cmd;

import lombok.AllArgsConstructor;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.VariableInstanceEntity;
import org.activiti.engine.impl.persistence.entity.VariableInstanceEntityManager;
import org.activiti.engine.impl.variable.VariableTypes;

import java.util.Map;

@AllArgsConstructor
public class AddExecutionVariables implements Command<Void> {
    private String executionId;
    private Map<String, Object> variables;

    @Override
    public Void execute(CommandContext commandContext) {
        VariableTypes variableTypes = Context.getProcessEngineConfiguration().getVariableTypes();
        VariableInstanceEntityManager variableInstanceEntityManager = commandContext.getVariableInstanceEntityManager();
        ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findById(executionId);
        //查询第一级的 executionEntity
        while (executionEntity.getParentId() != null) {
            executionEntity = commandContext.getExecutionEntityManager().findById(executionEntity.getParentId());
        }
        for (Map.Entry<String, Object> stringObjectEntry : variables.entrySet()) {
            VariableInstanceEntity variableInstanceEntity = variableInstanceEntityManager.create(stringObjectEntry.getKey(), variableTypes.findVariableType(stringObjectEntry.getValue()), stringObjectEntry.getValue());
            variableInstanceEntity.setExecution(executionEntity);
            commandContext.getVariableInstanceEntityManager().insert(variableInstanceEntity);
        }
        Map<String, Object> entityVariables = executionEntity.getVariables();
        entityVariables.putAll(this.variables);
        executionEntity.setVariables(entityVariables);
        return null;
    }
}
